/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.bookmarks.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Attachment;
import etcore.webapp.grouptalk.common.object.Comment;
import etcore.webapp.grouptalk.common.object.Directory;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.Topic;
import etcore.webapp.grouptalk.common.service.AttachmentService;
import etcore.webapp.grouptalk.common.service.DirectoryService;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.common.service.TopicService;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of showing
 * BOOKMARKS detail page,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class BookmarksViewAction extends AbstractAction {

	private static final long serialVersionUID = -7987513888797342571L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;

	// parameter/attributes constants

	public static final String KEY = "key";
	public static final String CURRENT_GROUP = "currentGroup";

	public static final String NAME_TAG = "name&tag";
	public static final String LAST_COMMENT = "lastComment";

	// utility constants

	public static final String START_PID = "startpid";
	public static final String END_PID = "endpid";

	// forward pages

	public static final String ERROR_PAGE = "/error.jsp";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {

		String gid = request.getParameter(PageConstants.GID);
		Group group = null;
		GroupService groupService = new GroupService();
		if (gid != null) {
			group = groupService.findById(new Integer(gid));
			if (group != null && group.getOpen() == 3) {
				request.setAttribute(CURRENT_GROUP, group);
				return ACCESS_ALLOWED;
			}
		}

		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (ERROR == validationResult)
			return ERROR_PAGE;
		return PageConstants.PAGE_PATH_BOOKMARKSVIEW;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub

		String tid = request.getParameter(PageConstants.TID);

		TopicService topicService = new TopicService();
		MessageService msgService = new MessageService();
		Group group = (Group) request.getAttribute(CURRENT_GROUP);
		if (group == null)
			return;
		DirectoryService directoryService = new DirectoryService();
		List<Directory> targetDirectories = directoryService.findByGid(group
				.getId());
		if (targetDirectories != null && targetDirectories.size() > 0) {
			request.setAttribute("currentDirectory", targetDirectories.get(0));
		}
		List<Topic> topics = topicService.findByProperty(PageConstants.GID,
				group.getId());
		request.setAttribute(PageConstants.TOPICS, topics);
		@SuppressWarnings("rawtypes")
		Map topicMap = new HashMap();
		for (Topic topic : topics) {
			long size = msgService.findSizeByProperty(PageConstants.TID,
					topic.getId());
			request.setAttribute(topic.getId() + PageConstants.SIZE, size);
			topicMap.put(topic.getId(), topic.getName());
		}
		request.setAttribute(PageConstants.TOPIC_MAP, topicMap);
		if (tid == null || tid.equals(Symbols.BLANK)) {
			if (topics != null && topics.size() > 0)
				request.setAttribute(PageConstants.TID, ((Topic) topics.get(0))
						.getId().toString());
		}

		getMessages(request, response);

	}

	/*
	 * Integer tempm_id=(Integer)tempm[0]; Integer tempm_tid=(Integer)tempm[1];
	 * String tempm_name=(String)tempm[2]; String *
	 * tempm_addtime=(String)tempm[3]; String tempm_userName=(String)tempm[4];
	 * Integer tempm_num=(Integer)tempm[5]; Integer tempm_up=(Integer)tempm[6];
	 * Integer tempm_flag=(Integer)tempm[7]; String tempm_tag=(String)tempm[8];
	 * String tempm_source=(String)tempm[9]; String
	 * tempm_stime=(String)tempm[10]; Integer
	 * commentNum=gmessdao.findCommentNum(tempm_id); Gcomment
	 * tmpG=gmessdao.findLastComment(tempm_id);
	 */

	private void getMessages(HttpServletRequest request,
			HttpServletResponse response) {
		int intpageid = 1;
		MessageService msgService = new MessageService();
		String gid = request.getParameter(PageConstants.GID);
		String tid = request.getParameter(PageConstants.TID);
		if (tid == null)
			tid = (String) request.getAttribute(PageConstants.TID);
		String key = request.getParameter(KEY);
		int unit = 10;
		@SuppressWarnings("rawtypes")
		List msgs = null;
		long all = 0;
		int begin = 0, pagenums = 0;
		String pageid = request.getParameter(PageConstants.PAGEID);
		if (pageid != null)
			intpageid = Integer.parseInt(pageid);
		if (tid != null && !tid.equals(Symbols.BLANK)) {

			if (key != null && !key.equals(Symbols.BLANK)) {
				all = msgService.searchSizeByPropertyAndTid(NAME_TAG, key,
						new Integer(tid));
				pagenums = (int) ((all + unit - 1) / unit);
				begin = unit * (intpageid - 1);
				msgs = msgService.searchByPropertyAndTid(NAME_TAG, key,
						new Integer(tid), begin, unit);
			} else {
				all = msgService.findSizeByProperty(PageConstants.TID,
						new Integer(tid));
				pagenums = (int) ((all + unit - 1) / unit);
				begin = unit * (intpageid - 1);
				msgs = msgService.findByProperty(PageConstants.TID,
						new Integer(tid), begin, unit);
			}

		} else {
			if (gid != null) {
				if (key != null && !key.equals(Symbols.BLANK)) {
					all = msgService.searchSizeByPropertyAndGid(NAME_TAG, key,
							new Integer(gid));
					pagenums = (int) ((all + unit - 1) / unit);
					begin = unit * (intpageid - 1);
					msgs = msgService.searchByPropertyAndGid(NAME_TAG, key,
							new Integer(gid), begin, unit);
				} else {
					all = msgService.findSizeByGid(new Integer(gid));
					pagenums = (int) ((all + unit - 1) / unit);
					begin = unit * (intpageid - 1);
					msgs = msgService.findMsgsByGid(new Integer(gid), begin,
							unit);
				}
			}
		}
		
		int startpid = intpageid - 3;
		if (startpid <= 0)
			startpid = 1;
		int endpid = intpageid + 8;
		if (intpageid > 8)
			endpid = intpageid + 6;
		if (endpid >= pagenums)
			endpid = pagenums;

		request.setAttribute(START_PID, startpid);
		request.setAttribute(END_PID, endpid);
		AttachmentService attachmentService = new AttachmentService();
		// comment count and time
		for (int k = 0; k < msgs.size(); k++) {
			Object[] tempm = (Object[]) msgs.get(k);
			Integer tempm_id = (Integer) tempm[0];
			Long commentNum = msgService.findCommentNum(tempm_id);
			Comment tmpG = msgService.findLastComment(tempm_id);
			request.setAttribute(tempm_id + PageConstants.COMMENT_NUM, commentNum);
			if (tmpG != null)
				request.setAttribute(tempm_id + LAST_COMMENT, tmpG.getTime());
			List<Attachment> attachments = attachmentService.findByProperty(
					PageConstants.GMID, tempm_id);

			if (attachments != null) {
				List<String> images = new ArrayList<String>();
				for (Attachment attachment : attachments) {
					String attached = attachment.getAttached();
					if (attached.endsWith("jpg") || attached.endsWith("JPG")
							|| attached.endsWith("gif")
							|| attached.endsWith("GIF")
							|| attached.endsWith("bmp")
							|| attached.endsWith("BMP")
							|| attached.endsWith("png")
							|| attached.endsWith("PNG"))
						images.add(attached);
				}
				request.setAttribute(tempm_id + "attachments", images);
			}
		}

		request.setAttribute(PageConstants.INTPAGEID, intpageid);
		request.setAttribute(PageConstants.PAGENUMS, pagenums);
		request.setAttribute(PageConstants.ALL, all);
		request.setAttribute(PageConstants.MSGS, msgs);

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

}
